<template>
  <div class="team-reports">
    <!-- 头部信息 -->
    <div class="header-section">
      <div class="team-info">
        <el-button type="text" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回团队列表
        </el-button>
        <h2 class="team-title">{{ teamInfo.name }} - 测评报告</h2>
        <p class="team-desc">{{ teamInfo.description }}</p>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="handleGenerateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button type="success" @click="handleExportReport">
          <el-icon><Download /></el-icon>
          导出报告
        </el-button>
        <el-button type="info" @click="handleShareReport">
          <el-icon><Share /></el-icon>
          分享报告
        </el-button>
      </div>
    </div>

    <!-- 报告概览 -->
    <div class="report-overview">
      <div class="overview-cards">
        <div class="overview-card">
          <div class="card-header">
            <h3>团队概况</h3>
            <el-icon class="card-icon"><User /></el-icon>
          </div>
          <div class="card-content">
            <div class="metric">
              <span class="metric-label">总成员数</span>
              <span class="metric-value">{{ reportData.overview.totalMembers }}</span>
            </div>
            <div class="metric">
              <span class="metric-label">完成测评</span>
              <span class="metric-value completed">{{ reportData.overview.completedAssessments }}</span>
            </div>
            <div class="metric">
              <span class="metric-label">完成率</span>
              <span class="metric-value">{{ reportData.overview.completionRate }}%</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-header">
            <h3>团队评分</h3>
            <el-icon class="card-icon"><TrophyBase /></el-icon>
          </div>
          <div class="card-content">
            <div class="score-circle">
              <el-progress
                type="circle"
                :percentage="reportData.overview.averageScore"
                :width="80"
                :stroke-width="8"
                :color="getScoreColor(reportData.overview.averageScore)"
              >
                <template #default="{ percentage }">
                  <span class="score-text">{{ percentage }}</span>
                </template>
              </el-progress>
            </div>
            <p class="score-desc">团队平均得分</p>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-header">
            <h3>报告状态</h3>
            <el-icon class="card-icon"><DocumentChecked /></el-icon>
          </div>
          <div class="card-content">
            <div class="status-info">
              <el-tag :type="getReportStatusType(reportData.overview.reportStatus)" size="large">
                {{ getReportStatusText(reportData.overview.reportStatus) }}
              </el-tag>
              <p class="status-time">{{ reportData.overview.lastUpdateTime }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细报告内容 -->
    <div class="report-content">
      <el-tabs v-model="activeReportTab" class="report-tabs">
        <!-- 能力分析 -->
        <el-tab-pane label="能力分析" name="ability">
          <div class="ability-analysis">
            <div class="analysis-header">
              <h3>团队能力分布</h3>
              <p>基于团队成员测评结果的综合能力分析</p>
            </div>

            <!-- 能力雷达图 -->
            <div class="chart-container">
              <div class="chart-card">
                <h4>团队能力雷达图</h4>
                <div class="radar-chart" ref="radarChartRef"></div>
              </div>
              <div class="chart-card">
                <h4>能力分项得分</h4>
                <div class="ability-scores">
                  <div
                    v-for="ability in reportData.abilities"
                    :key="ability.name"
                    class="ability-item"
                  >
                    <div class="ability-info">
                      <span class="ability-name">{{ ability.name }}</span>
                      <span class="ability-score">{{ ability.score }}</span>
                    </div>
                    <el-progress
                      :percentage="ability.score"
                      :stroke-width="12"
                      :color="getAbilityColor(ability.score)"
                    />
                    <p class="ability-desc">{{ ability.description }}</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- 能力优势与改进建议 -->
            <div class="suggestions-section">
              <div class="suggestion-card strengths">
                <h4>
                  <el-icon><Trophy /></el-icon>
                  团队优势
                </h4>
                <ul>
                  <li v-for="strength in reportData.strengths" :key="strength">
                    {{ strength }}
                  </li>
                </ul>
              </div>
              <div class="suggestion-card improvements">
                <h4>
                  <el-icon><Tools /></el-icon>
                  改进建议
                </h4>
                <ul>
                  <li v-for="improvement in reportData.improvements" :key="improvement">
                    {{ improvement }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 成员详情 -->
        <el-tab-pane label="成员详情" name="members">
          <div class="members-detail">
            <div class="detail-header">
              <h3>成员测评详情</h3>
              <div class="header-actions">
                <el-select v-model="memberFilter" placeholder="筛选成员" clearable>
                  <el-option label="全部成员" value="" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="进行中" value="in-progress" />
                  <el-option label="未开始" value="not-started" />
                </el-select>
              </div>
            </div>

            <div class="members-grid">
              <div
                v-for="member in filteredMemberReports"
                :key="member.id"
                class="member-report-card"
              >
                <div class="member-header">
                  <el-avatar :size="48" :src="member.avatar">
                    {{ member.name.charAt(0) }}
                  </el-avatar>
                  <div class="member-info">
                    <h4>{{ member.name }}</h4>
                    <p>{{ member.position }}</p>
                  </div>
                  <el-tag
                    :type="getStatusTagType(member.status)"
                    size="small"
                  >
                    {{ getStatusText(member.status) }}
                  </el-tag>
                </div>
                
                <div class="member-scores" v-if="member.status === 'completed'">
                  <div class="overall-score">
                    <span class="score-label">综合得分</span>
                    <span class="score-value">{{ member.overallScore }}</span>
                  </div>
                  <div class="ability-bars">
                    <div
                      v-for="ability in member.abilities"
                      :key="ability.name"
                      class="ability-bar"
                    >
                      <div class="bar-header">
                        <span>{{ ability.name }}</span>
                        <span>{{ ability.score }}</span>
                      </div>
                      <el-progress
                        :percentage="ability.score"
                        :stroke-width="6"
                        :show-text="false"
                        :color="getAbilityColor(ability.score)"
                      />
                    </div>
                  </div>
                </div>

                <div class="member-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleViewMemberReport(member)"
                    :disabled="member.status !== 'completed'"
                  >
                    查看详情
                  </el-button>
                  <el-button
                    type="info"
                    size="small"
                    @click="handleInviteMember(member)"
                    v-if="member.status !== 'completed'"
                  >
                    邀请测评
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 对比分析 -->
        <el-tab-pane label="对比分析" name="comparison">
          <div class="comparison-analysis">
            <div class="comparison-header">
              <h3>团队对比分析</h3>
              <p>与行业标准和历史数据的对比分析</p>
            </div>

            <div class="comparison-charts">
              <div class="chart-card">
                <h4>能力对比</h4>
                <div class="comparison-chart" ref="comparisonChartRef"></div>
              </div>
              <div class="chart-card">
                <h4>趋势分析</h4>
                <div class="trend-chart" ref="trendChartRef"></div>
              </div>
            </div>

            <div class="benchmark-section">
              <h4>行业基准对比</h4>
              <div class="benchmark-table">
                <el-table :data="reportData.benchmarks" style="width: 100%">
                  <el-table-column prop="dimension" label="能力维度" width="200" />
                  <el-table-column prop="teamScore" label="团队得分" width="120">
                    <template #default="scope">
                      <span class="score-badge">{{ scope.row.teamScore }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="industryAverage" label="行业平均" width="120">
                    <template #default="scope">
                      <span class="score-badge industry">{{ scope.row.industryAverage }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="difference" label="差异" width="120">
                    <template #default="scope">
                      <span
                        :class="['difference-badge', scope.row.difference > 0 ? 'positive' : 'negative']"
                      >
                        {{ scope.row.difference > 0 ? '+' : '' }}{{ scope.row.difference }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ranking" label="行业排名" />
                </el-table>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Document, Download, Share, User, TrophyBase, 
  DocumentChecked, Trophy, Tools
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const activeReportTab = ref('ability')
const memberFilter = ref('')
const radarChartRef = ref()
const comparisonChartRef = ref()
const trendChartRef = ref()

// 团队信息
const teamInfo = reactive({
  id: 1,
  name: '产品研发团队',
  description: '负责核心产品的研发与技术创新，包含前端、后端、UI/UX等多个角色'
})

// 报告数据
const reportData = reactive({
  overview: {
    totalMembers: 12,
    completedAssessments: 10,
    completionRate: 83,
    averageScore: 85,
    reportStatus: 'generated',
    lastUpdateTime: '2024-08-13 16:30:00'
  },
  abilities: [
    {
      name: '技术能力',
      score: 88,
      description: '团队在技术实现和创新方面表现优异'
    },
    {
      name: '沟通协作',
      score: 82,
      description: '团队协作良好，但仍有提升空间'
    },
    {
      name: '学习适应',
      score: 85,
      description: '团队学习能力强，适应性较好'
    },
    {
      name: '创新思维',
      score: 79,
      description: '创新意识有待进一步提升'
    },
    {
      name: '执行力',
      score: 91,
      description: '团队执行力强，目标达成率高'
    },
    {
      name: '领导力',
      score: 76,
      description: '领导力发展需要加强培养'
    }
  ],
  strengths: [
    '技术实力雄厚，拥有扎实的专业技能基础',
    '执行力强，能够高效完成既定目标',
    '学习适应能力较强，能够快速掌握新技术',
    '团队稳定性好，成员配合默契'
  ],
  improvements: [
    '加强创新思维培训，提升团队创新能力',
    '建立更有效的沟通机制，提高协作效率',
    '培养和发展团队中的领导人才',
    '定期组织团队建设活动，增强凝聚力'
  ],
  memberReports: [
    {
      id: 1,
      name: '张三',
      position: '前端工程师',
      avatar: '',
      status: 'completed',
      overallScore: 87,
      abilities: [
        { name: '技术能力', score: 92 },
        { name: '沟通协作', score: 85 },
        { name: '学习适应', score: 88 },
        { name: '创新思维', score: 82 },
        { name: '执行力', score: 90 }
      ]
    },
    {
      id: 2,
      name: '李四',
      position: '后端工程师',
      avatar: '',
      status: 'completed',
      overallScore: 89,
      abilities: [
        { name: '技术能力', score: 95 },
        { name: '沟通协作', score: 80 },
        { name: '学习适应', score: 87 },
        { name: '创新思维', score: 85 },
        { name: '执行力', score: 92 }
      ]
    },
    {
      id: 3,
      name: '王五',
      position: '产品经理',
      avatar: '',
      status: 'in-progress',
      overallScore: null,
      abilities: []
    },
    {
      id: 4,
      name: '赵六',
      position: 'UI设计师',
      avatar: '',
      status: 'completed',
      overallScore: 83,
      abilities: [
        { name: '技术能力', score: 88 },
        { name: '沟通协作', score: 85 },
        { name: '学习适应', score: 82 },
        { name: '创新思维', score: 90 },
        { name: '执行力', score: 80 }
      ]
    }
  ],
  benchmarks: [
    {
      dimension: '技术能力',
      teamScore: 88,
      industryAverage: 82,
      difference: 6,
      ranking: '前25%'
    },
    {
      dimension: '沟通协作',
      teamScore: 82,
      industryAverage: 85,
      difference: -3,
      ranking: '中等水平'
    },
    {
      dimension: '学习适应',
      teamScore: 85,
      industryAverage: 80,
      difference: 5,
      ranking: '前30%'
    },
    {
      dimension: '创新思维',
      teamScore: 79,
      industryAverage: 83,
      difference: -4,
      ranking: '中等偏下'
    },
    {
      dimension: '执行力',
      teamScore: 91,
      industryAverage: 78,
      difference: 13,
      ranking: '前10%'
    }
  ]
})

// 计算属性
const filteredMemberReports = computed(() => {
  if (!memberFilter.value) {
    return reportData.memberReports
  }
  return reportData.memberReports.filter(member => member.status === memberFilter.value)
})

// 方法
const goBack = () => {
  router.push('/dashboard/assessment/team')
}

const getScoreColor = (score) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#e6a23c'
  if (score >= 70) return '#f56c6c'
  return '#909399'
}

const getAbilityColor = (score) => {
  if (score >= 85) return '#67c23a'
  if (score >= 75) return '#e6a23c'
  if (score >= 65) return '#f56c6c'
  return '#909399'
}

const getReportStatusType = (status) => {
  const statusMap = {
    'generated': 'success',
    'generating': 'warning',
    'pending': 'info'
  }
  return statusMap[status] || 'info'
}

const getReportStatusText = (status) => {
  const statusMap = {
    'generated': '已生成',
    'generating': '生成中',
    'pending': '待生成'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const statusMap = {
    'completed': 'success',
    'in-progress': 'warning',
    'not-started': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'completed': '已完成',
    'in-progress': '进行中',
    'not-started': '未开始'
  }
  return statusMap[status] || '未知'
}

const handleGenerateReport = () => {
  ElMessageBox.confirm(
    '确定要重新生成团队测评报告吗？这将覆盖当前报告。',
    '重新生成报告',
    {
      confirmButtonText: '确定生成',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('报告生成中，请稍候...')
    // 模拟生成过程
    setTimeout(() => {
      ElMessage.success('团队测评报告生成成功！')
      reportData.overview.lastUpdateTime = new Date().toLocaleString('zh-CN')
    }, 2000)
  }).catch(() => {
    // 用户取消
  })
}

const handleExportReport = () => {
  ElMessage.success('报告导出成功')
}

const handleShareReport = () => {
  ElMessageBox.prompt('请输入分享给的邮箱地址：', '分享报告', {
    confirmButtonText: '发送',
    cancelButtonText: '取消',
    inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    inputErrorMessage: '邮箱地址格式不正确'
  }).then(({ value }) => {
    ElMessage.success(`报告已发送至 ${value}`)
  }).catch(() => {
    // 用户取消
  })
}

const handleViewMemberReport = (member) => {
  ElMessage.info(`查看 ${member.name} 的详细报告`)
  // 这里可以跳转到个人报告页面或显示详细弹窗
}

const handleInviteMember = (member) => {
  ElMessageBox.confirm(
    `确定要向 ${member.name} 发送测评邀请吗？`,
    '邀请测评',
    {
      confirmButtonText: '确定发送',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.success(`已向 ${member.name} 发送测评邀请`)
  }).catch(() => {
    // 用户取消
  })
}

// 初始化图表
const initCharts = () => {
  // 这里可以使用 ECharts 或其他图表库来初始化图表
  // 由于没有安装图表库，这里只是占位
  console.log('初始化图表')
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.team-reports {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.header-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.back-btn {
  color: white !important;
  padding: 8px 0;
  margin-bottom: 12px;
  font-size: 14px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}

.team-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.team-desc {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.action-buttons .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.report-overview {
  padding: 24px;
  background: #f8fafc;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.overview-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.card-icon {
  font-size: 24px;
  color: #667eea;
}

.card-content .metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.metric-label {
  color: #718096;
  font-size: 14px;
}

.metric-value {
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.metric-value.completed {
  color: #38a169;
}

.score-circle {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.score-text {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.score-desc {
  text-align: center;
  color: #718096;
  margin: 0;
  font-size: 14px;
}

.status-info {
  text-align: center;
}

.status-time {
  margin: 12px 0 0 0;
  color: #718096;
  font-size: 14px;
}

.report-content {
  padding: 24px;
}

.report-tabs {
  background: white;
}

.analysis-header, .detail-header, .comparison-header {
  margin-bottom: 24px;
}

.analysis-header h3, .detail-header h3, .comparison-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.analysis-header p, .comparison-header p {
  margin: 0;
  color: #718096;
  font-size: 14px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container, .comparison-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

.chart-card {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e2e8f0;
}

.chart-card h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.radar-chart, .comparison-chart, .trend-chart {
  height: 300px;
  background: white;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #718096;
  border: 2px dashed #e2e8f0;
}

.ability-scores {
  margin-bottom: 16px;
}

.ability-item {
  margin-bottom: 20px;
}

.ability-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.ability-name {
  font-weight: 500;
  color: #1a202c;
}

.ability-score {
  font-weight: 600;
  color: #667eea;
}

.ability-desc {
  margin: 8px 0 0 0;
  font-size: 12px;
  color: #718096;
}

.suggestions-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.suggestion-card {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  border-left: 4px solid #667eea;
}

.suggestion-card.strengths {
  border-left-color: #38a169;
  background: #f0fff4;
}

.suggestion-card.improvements {
  border-left-color: #ed8936;
  background: #fffaf0;
}

.suggestion-card h4 {
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.suggestion-card ul {
  margin: 0;
  padding-left: 20px;
}

.suggestion-card li {
  margin-bottom: 8px;
  color: #4a5568;
  line-height: 1.5;
}

.members-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.member-report-card {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 20px;
  transition: box-shadow 0.2s;
}

.member-report-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.member-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.member-info {
  flex: 1;
}

.member-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.member-info p {
  margin: 0;
  font-size: 14px;
  color: #718096;
}

.member-scores {
  margin-bottom: 16px;
}

.overall-score {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f7fafc;
  border-radius: 6px;
}

.score-label {
  font-weight: 500;
  color: #4a5568;
}

.score-value {
  font-size: 20px;
  font-weight: 600;
  color: #667eea;
}

.ability-bars {
  margin-bottom: 8px;
}

.ability-bar {
  margin-bottom: 12px;
}

.bar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  font-size: 14px;
}

.member-actions {
  display: flex;
  gap: 8px;
}

.benchmark-section {
  margin-top: 32px;
}

.benchmark-section h4 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.benchmark-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.score-badge {
  display: inline-block;
  padding: 4px 8px;
  background: #667eea;
  color: white;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.score-badge.industry {
  background: #718096;
}

.difference-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.difference-badge.positive {
  background: #c6f6d5;
  color: #2f855a;
}

.difference-badge.negative {
  background: #fed7d7;
  color: #c53030;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}
</style>
